package org.jeecg.modules.util;

import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WordTemplateFilterUtils {
    public static void main(String[] args) {
        try {
            XWPFDocument doc = new XWPFDocument(new FileInputStream("体育老师资质文件.docx"));
            // 创建一个HashMap来存储要替换的数据
            Map<String, String> replacements = new HashMap<>();
//            replacements.put("area", "内蒙古自治区鄂尔多斯市");
            replacements.put("schoolName", "鄂尔多斯市康巴什区第十小学");
            replacements.put("caseName","“点亮童趣 乐享运动”—XX学校阳光⼤课间集体操作案例");

            // 遍历文档中的所有段落，查找并替换占位符
            for (XWPFParagraph paragraph : doc.getParagraphs()) {
                replaceTextInParagraph(paragraph, replacements);
            }
            // 遍历文档中的所有表格（如果有的话）
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph p : cell.getParagraphs()) {
                            replaceTextInParagraph(p, replacements);
                        }
                    }
                }
            }
            // 保存修改后的文档
            try (FileOutputStream out = new FileOutputStream("e:\\2.docx")) {
                doc.write(out);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void replaceTextInParagraph(XWPFParagraph paragraph, Map<String, String> replacements) {
        // 获取段落中的运行内容（Runs）并替换文本
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0); // 获取运行中的文本内容
            if (text != null) {
                for (Map.Entry<String, String> entry : replacements.entrySet()) {
                    text = text.replace("${" + entry.getKey() + "}", entry.getValue()); // 替换文本占位符
                }
                run.setText(text, 0); // 设置新的文本内容到运行中
            }
        }
    }


}